from PyQt6.QtWidgets import (
    QFrame,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QTableWidget,
    QTableWidgetItem,
    QHeaderView,
    QLineEdit,
    QComboBox,
    QMessageBox,
    QDialog,
    QFileDialog,
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap
import base64
import os
from http_client import http_client
from utils.style_manager import StyleManager
from database import db_manager

# 尝试导入二维码识别库
try:
    import cv2
    from pyzbar import pyzbar
    QR_READER_AVAILABLE = True
except ImportError:
    QR_READER_AVAILABLE = False
    print("警告: 未安装二维码识别库，请安装: pip install opencv-python pyzbar")

class FriendPage(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        
    def setup_ui(self):
        """设置新好友页面UI（添加新好友）"""
        page_layout = QVBoxLayout(self)
        page_layout.setSpacing(10)
        
        # 控制区域
        control_frame = QFrame()
        control_layout = QVBoxLayout(control_frame)  # 改为垂直布局以容纳多行
        control_layout.setSpacing(15)
        
        # 第一行：添加好友功能
        friend_row = QHBoxLayout()
        friend_row.setSpacing(15)
        
        # 添加账号（操作者）
        operator_label = QLabel("操作账号:")
        StyleManager.set_label_style(operator_label, "subtitle")
        friend_row.addWidget(operator_label)

        self.operator_combo = QComboBox()
        friend_row.addWidget(self.operator_combo)

        # 目标微信号/手机号
        target_label = QLabel("好友ID/手机号:")
        StyleManager.set_label_style(target_label, "subtitle")
        friend_row.addWidget(target_label)

        self.target_edit = QLineEdit()
        self.target_edit.setPlaceholderText("输入好友wxid/微信号/手机号")
        self.target_edit.setFixedWidth(220)
        friend_row.addWidget(self.target_edit)

        friend_row.addStretch()

        # 搜索按钮
        self.search_btn = QPushButton("搜索")
        StyleManager.set_button_style(self.search_btn, "info")
        self.search_btn.clicked.connect(self.on_search_friend)
        friend_row.addWidget(self.search_btn)
        
        control_layout.addLayout(friend_row)
        
        # 第二行：扫码进群功能
        qr_row = QHBoxLayout()
        qr_row.setSpacing(15)
        
        # 扫码进群标签
        qr_label = QLabel("扫码进群:")
        StyleManager.set_label_style(qr_label, "subtitle")
        qr_row.addWidget(qr_label)
        
        # 上传二维码按钮
        self.upload_qr_btn = QPushButton("上传二维码")
        StyleManager.set_button_style(self.upload_qr_btn, "primary")
        self.upload_qr_btn.clicked.connect(self.upload_qr_code)
        qr_row.addWidget(self.upload_qr_btn)
        
        # 二维码图片路径显示
        self.qr_preview_label = QLabel("未选择图片")
        self.qr_preview_label.setFixedSize(200, 60)
        self.qr_preview_label.setStyleSheet("border: 1px solid #ccc; background-color: #f5f5f5; padding: 5px;")
        self.qr_preview_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        self.qr_preview_label.setWordWrap(True)
        qr_row.addWidget(self.qr_preview_label)
        
        # 二维码URL显示
        self.qr_url_label = QLabel("二维码URL:")
        qr_row.addWidget(self.qr_url_label)
        
        self.qr_url_edit = QLineEdit()
        self.qr_url_edit.setPlaceholderText("二维码图片URL或上传后自动识别")
        self.qr_url_edit.setFixedWidth(300)
        qr_row.addWidget(self.qr_url_edit)
        
        qr_row.addStretch()
        
        # 扫码进群按钮
        self.scan_join_btn = QPushButton("扫码进群")
        StyleManager.set_button_style(self.scan_join_btn, "success")
        self.scan_join_btn.clicked.connect(self.scan_into_group)
        qr_row.addWidget(self.scan_join_btn)
        
        control_layout.addLayout(qr_row)
        
        page_layout.addWidget(control_frame)
        
        # 结果记录表格
        self.main_table = QTableWidget()
        self.main_table.setColumnCount(5)
        self.main_table.setHorizontalHeaderLabels([
            "No", "操作账号", "目标", "结果", "时间"
        ])
        
        # 设置表格撑满容器
        self.main_table.horizontalHeader().setStretchLastSection(True)
        self.main_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        
        # 隐藏垂直表头
        self.main_table.verticalHeader().setVisible(False)
        
        # 设置表格样式
        self.main_table.setAlternatingRowColors(True)
        self.main_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.main_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        
        self.main_table.setRowCount(0)  # 空白表格
        
        page_layout.addWidget(self.main_table)
        
        self.refresh_operator_accounts()
        
        # 初始化二维码相关变量
        self.qr_image_path = ""
        self.qr_image_url = ""
    
    def refresh_operator_accounts(self):
        """刷新操作账号列表（在线账号）"""
        try:
            self.operator_combo.clear()
            accounts = db_manager.get_online_accounts()
            for acc in accounts:
                display = acc.get('nick_name') or acc.get('user_name', '')
                self.operator_combo.addItem(display, acc)
        except Exception as e:
            print(f"加载操作账号失败: {e}")

    def on_search_friend(self):
        """先根据手机号/微信号搜索好友"""
        operator = self.operator_combo.currentData()
        if not operator:
            QMessageBox.warning(self, "提示", "请先选择操作账号")
            return
        target = (self.target_edit.text() or '').strip()
        if not target:
            QMessageBox.warning(self, "提示", "请输入好友ID/手机号")
            return
        try:
            wxid = operator.get('user_name', '')
            resp = http_client.search_friend(wxid, target)
            ok = bool(resp.get('Success', False)) and resp.get('Code', -1) == 0
            if ok:
                # 解析搜索结果中的昵称与可用的目标ID（字段为 { 'string': '...' } 结构）
                data = resp.get('Data', {}) if isinstance(resp.get('Data'), dict) else {}
                def get_data_string(key: str) -> str:
                    val = data.get(key)
                    if isinstance(val, dict):
                        return val.get('string') or val.get('String') or ''
                    return val or ''
                nickname = get_data_string('NickName') or get_data_string('QuanPin') or target
                v1 = get_data_string('UserName') if get_data_string('UserName') else ''
                v2 = get_data_string('AntispamTicket') if get_data_string('AntispamTicket') else ''
                scene = 3 if self.target_edit.text().startswith('wxid_') else 15

                from PyQt6.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton
                class VerificationDialog(QDialog):
                    def __init__(self, operator, nickname, parent=None):
                        super().__init__(parent)
                        self.setWindowTitle("确认添加好友")
                        self.setModal(True)
                        self.setMinimumWidth(360)

                        layout = QVBoxLayout()
                        layout.setSpacing(10)
                        layout.setContentsMargins(16, 16, 16, 16)

                        title_label = QLabel("请确认添加以下好友")
                        StyleManager.set_label_style(title_label, "subtitle")
                        layout.addWidget(title_label)

                        info_label = QLabel(f"操作账号: {operator.get('user_name', '')}")
                        layout.addWidget(info_label)

                        nick_label = QLabel(f"目标昵称: {nickname}")
                        layout.addWidget(nick_label)

                        self.verification_input = QLineEdit()
                        self.verification_input.setPlaceholderText("验证消息（可留空）")
                        layout.addWidget(self.verification_input)

                        btn_row = QHBoxLayout()
                        btn_row.addStretch()
                        send_button = QPushButton("发送")
                        StyleManager.set_button_style(send_button, "success")
                        send_button.setDefault(True)
                        send_button.clicked.connect(self.accept)
                        cancel_button = QPushButton("取消")
                        StyleManager.set_button_style(cancel_button, "danger")
                        cancel_button.clicked.connect(self.reject)
                        btn_row.addWidget(cancel_button)
                        btn_row.addWidget(send_button)

                        layout.addLayout(btn_row)
                        self.setLayout(layout)

                    def get_verification_message(self):
                        return self.verification_input.text()

                # 使用自定义对话框
                dialog = VerificationDialog(operator, nickname, self)
                if dialog.exec():
                    verification_message = dialog.get_verification_message()
                    try:
                        wxid = operator.get('user_name', '')
                        resp_add = http_client.request_friend(wxid, v1, v2, scene, verification_message)
                        ok_add = bool(resp_add.get('Success', False)) and resp_add.get('Code', -1) == 0 and resp_add.get('Data', {}).get('BaseResponse', {}).get('ret', -1) == 0
                        if ok_add:
                            result_text = "发送成功"
                        else:
                            result_text = resp_add.get('Message') or "发送失败"
                            if resp_add.get('Data', {}).get('BaseResponse', {}).get('ret', -1) == 408:
                                result_text = "发送失败，目标账号已添加过好友"
                    except Exception as e:
                        result_text = f"错误: {e}"
                    self.append_log_row(operator.get('user_name', ''), nickname, result_text)
            else:
                QMessageBox.warning(self, "搜索结果", resp.get('Message') or "未找到或不可添加")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"搜索失败: {e}")

    def extract_qr_code_url(self, image_path: str) -> str:
        """从图片中提取二维码URL"""
        if not QR_READER_AVAILABLE:
            return ""
        
        try:
            # 读取图片
            image = cv2.imread(image_path)
            if image is None:
                return ""
            
            # 转换为灰度图
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            
            # 使用pyzbar检测二维码
            barcodes = pyzbar.decode(gray)
            
            if barcodes:
                # 获取第一个检测到的二维码内容
                qr_data = barcodes[0].data.decode('utf-8')
                return qr_data
            else:
                return ""
                
        except Exception as e:
            print(f"二维码识别失败: {e}")
            return ""

    def upload_qr_code(self):
        """上传二维码图片并识别其中的URL"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择二维码图片", 
            "", 
            "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)"
        )
        
        if file_path:
            self.qr_image_path = file_path
            # 显示图片路径
            self.qr_preview_label.setText(file_path)
            self.qr_preview_label.setStyleSheet("border: 1px solid #ccc; background-color: #f5f5f5; padding: 5px;")
            
            # 尝试从图片中提取二维码URL
            if QR_READER_AVAILABLE:
                qr_url = self.extract_qr_code_url(file_path)
                if qr_url:
                    self.qr_image_url = qr_url
                    self.qr_url_edit.setText(qr_url)
                    QMessageBox.information(self, "成功", f"二维码识别成功！\n提取的URL: {qr_url[:100]}...")
                else:
                    QMessageBox.warning(self, "警告", "未能从图片中识别出二维码内容")
                    self.qr_image_url = ""
            else:
                # 如果没有安装二维码识别库，提示用户手动输入
                QMessageBox.information(self, "提示", "未安装二维码识别库，请手动输入二维码URL\n安装命令: pip install opencv-python pyzbar")
                self.qr_image_url = ""
    
    def scan_into_group(self):
        """扫码进群"""
        operator = self.operator_combo.currentData()
        if not operator:
            QMessageBox.warning(self, "提示", "请先选择操作账号")
            return
            
        qr_url = self.qr_url_edit.text().strip()
        if not qr_url:
            QMessageBox.warning(self, "提示", "请输入二维码URL或上传二维码图片")
            return
            
        try:
            wxid = operator.get('user_name', '')
            resp = http_client.scan_into_group_enterprise(wxid, qr_url)
            ok = bool(resp.get('Success', False)) and resp.get('Code', -1) == 0
            if ok:
                result_text = "扫码进群成功"
                QMessageBox.information(self, "成功", "扫码进群成功！")
            else:
                result_text = resp.get('Message') or "扫码进群失败"
                QMessageBox.warning(self, "失败", result_text)
                
            # 记录到表格
            self.append_log_row(operator.get('user_name', ''), f"扫码进群: {qr_url[:50]}...", result_text)
            
        except Exception as e:
            error_msg = f"扫码进群失败: {e}"
            QMessageBox.critical(self, "错误", error_msg)
            self.append_log_row(operator.get('user_name', ''), f"扫码进群: {qr_url[:50]}...", error_msg)

    def append_log_row(self, operator_wxid: str, target: str, result: str):
        from datetime import datetime
        row = self.main_table.rowCount()
        self.main_table.insertRow(row)
        self.main_table.setItem(row, 0, QTableWidgetItem(str(row + 1)))
        self.main_table.setItem(row, 1, QTableWidgetItem(operator_wxid))
        self.main_table.setItem(row, 2, QTableWidgetItem(target))
        self.main_table.setItem(row, 3, QTableWidgetItem(result))
        self.main_table.setItem(row, 4, QTableWidgetItem(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))